<?php
/**
 * @filesource modules/event/controllers/IndexController.php
 * @author Hoang
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 */ 
class Home_GomeController extends Clu_Controller_Action_Hvn
{
	public $m,$c;//, $mPlace, $mArticle;
	public $tl;
	public function init()
	{
		//require_once (APP_PATH.'/modules/category/Model/Category.php');
		//require_once (APP_PATH.'/modules/news/Model/News.php');
		//require_once (APP_PATH.'/modules/article/Model/Article.php');
		//require_once (APP_PATH.'/modules/user/Model/User.php');
		$this->c = new category_Model_Category();
		$this->mArticle = new article_Model_Service();
		$this->n = new Model_News();
		parent::init();
		
	}
	
	public function indexAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);

//		$
 		$this->renderToHolder('index/home_address_background.phtml', false, null, 4,0);
 		$this->renderToHolder('index/ads.phtml', false, null, 4,1); 
//		$vision = $this->n->
		$vision = $this->n->getNewsData(1, true, 'array'); //vision
		$this->view->vision = $vision;

		/*
		$p = $this->n->findByPrimary(2); //vision
		$ph = $this->n->transformToFormArray($p, false);
		$this->view->philosophy = $ph;
		*/
		$ph = $this->n->getNewsData(2, true, 'array');
		$this->view->philosophy = $ph;
		

		$m = $this->n->getNewsData(3, true, 'array');
		$this->view->mission = $m;
		
//				
//		$m = $this->n->findByPrimary(3); //vision
//		$mi = $this->n->transformToFormArray($m, false);
//		$this->view->mission = $mi;
		$this->view->language = $sess->viewLang;
		$this->renderToHolder('index/company_vision.phtml', false, null, 4, 2);
		
		$this->renderToHolder('index/global_connection.phtml', false, null, 4, 3);
		$this->generateCommonBoxes();		
	}
	
	public function generateCommonBoxes()
	{
		$latest = '';//$this->n->getLatestRecruitments();
		$this->view->latest = $latest;
		$this->renderToHolder('index/latest_news.phtml', false, null, 5, 1);
		
		//$recruitment = $this->n->getLatestRecruitments();
		$this->renderToHolder('index/herevn.phtml', false, null, 5, 2);
		$this->renderToHolder('index/partners.phtml', false, null, 5, 3);
		$this->renderToHolder('index/footer.phtml', false, null, 6, 1); //footer
	}
	
	public function newsAction() 
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$this->view->language = $sess->viewLang;
		
		$id = $this->_request->getParam('id');
		
		$news = $this->n->getNewsData($id, true, 'array');
		
		$this->view->news = $news;
        $this->renderToHolder('index/news.phtml', false, null, 4,2);
         
        $this->generateCommonBoxes();
	}
	

	/**
	 * new tour leg action.
	 * 		/en/tour/new-tleg?tid=12&step=1
     */
	public function newTlegAction() 
	{
		//check user permissions here
		$sess = new Zend_Session_Namespace(CLU_NS);
		if (strpos ($sess->userPermissions, 'create tour') === false)
		{
                $this->view->errorMessage = __("You do not have the permission to do this");
                $this->renderToHolder( 'common/error.phtml');
                return;
        }
		//check if tourId is available
        $id = $this->_request->getParam("tid");
        if(!$tour = $this->m->getTourData($id, true, true)) //get tour article & tour leg article
        {
            $this->view->errorMessage = __('invalid tour id specified');
            $this->renderToHolder( 'common/error.phtml', false, null, 4, 1);	
            return;
        }
        $this->view->tid = $id;
        //if legNumber is not specified, then we get the number of current legs plus 1
        $legNumber = $this->_request->getParam("leg_number") ? $this->_request->getParam("leg_number") : (count($tour['legs']) + 1);
		$this->view->leg_number = $legNumber;
        $this->view->tour = $tour;
        $this->view->form = new Form_TLeg();
        $this->view->form->cluBuild(array ('action' => 'new', 'view' => $this->view, 'userPermissions' => $sess->userPermissions, 'tid' =>$id, 'leg_number' => $legNumber));
     
        if ($this->_request->isPost() && $this->view->form->isValid($_REQUEST)) 
        {
        	$data = $this->_request->getParams();
        	$db = $this->db;
	        $db->beginTransaction();
            try 
            {
            	//get article content
            	$defaultStatus = Zend_Registry::get('configuration')->general->defaultNodeStatus;
            	$data['article_title'] = $tour['name'] . "leg #" . $legNumber;
            	$data['article_body']  = $data['description'];
            	$data['article_status'] = isset($data['status']) ? $data['status'] : $defaultStatus;
            	$data['article_module'] = 'tleg';
            	$data['article_language'] = $tour['lang'];
            	$data['poster_id'] =  Zend_Auth::getInstance()->getIdentity()->id;
				
                if ($article_id = $this->mArticle->insertRaw($data,false))
                {
                    $data['article_id'] = $article_id; 
                	try         	
    		    	{
    		    	   	$this->tl->insertRaw($data,false);
    		    	}
    		    	catch (Exception $e) 
    		    	{
    		    		$this->mArticle->deleteByPrimary($article_id,false); //no need for atomicity
    		    	    $this->view->errorMessage .= $e->getMessage();//__("Could not insert tour");
    		    	    die($this->view->errorMessage);
    		    	}
                     $db->commit();
                }
                else
                {
                	$this->view->errorMessage .= __("Could not insert article");
                }
            }
            catch (Exception $ex)
            {
                $db->rollBack();
                $this->view->errorMessage .= $ex->getMessage() . __("Could not perform transaction");
            }
            
            //forward the 
	    	if (empty($this->view->errorMessage) && $data['is_last_leg'])
	    	{
				$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action'=>'success','module'=>'tour')) . 
															'?tid=' . $id);
	    	}
	    	elseif (empty($this->view->errorMessage))
			{
				$nextLeg = $legNumber + 1;
				//forward to the create next leg
				$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action'=>'new-tleg','module'=>'tour')) . 
															'?tid='.$id.'&leg_number='.$nextLeg);
			}			 	
        }
        $this->renderToHolder('index/new_tleg.phtml'); 
    	return;
	}
	
		
	public function viewAction() 
	{
		$id = $this->_request->getParam("id");
    	if(!$tour = $this->m->getTourData($id, true, true)) //get tour article & tour leg article
        {
            $this->view->errorMessage = __('Cannot find the requested tour');
            $this->renderToHolder('common/error.phtml');
            return;
        }

        $this->view->tour = $tour;
        
		$sess = new Zend_Session_Namespace(CLU_NS);
        $auth = Zend_Auth::getInstance();
        $this->view->edit_allowed = false;
        if (strpos ($sess->userPermissions, 'update tour'))//tour admin
        	$this->view->edit_allowed = true;
		elseif ($auth->hasIdentity())
		{
            $uIdentity = $auth->getIdentity();
    		if ($uIdentity->id == $tour['poster_id'] && strpos ($sess->userPermissions, 'update own tour'))
    		{
    			$this->view->edit_allowed = true;
    		}
        }
        		
        $this->renderToHolder('index/view.phtml'); 
	}
	
	public function editAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if(!$tour = $this->m->getTourData($id, true, false)) //get tour article & tour leg article
        {              
            $this->view->errorMessage = __('Cannot find the requested event');
            $this->renderToHolder('common/error.phtml');
            return;
        }
		//check for permission here
		//check rights
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = __('Not allowed to edit this user information. Check if your session expired');
            $this->renderToHolder('common/error.phtml');
            return;
		}

		$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		//if not admin
		// or not owner
		if (($uIdentity->id != $tour['poster_id'] && strpos ($sess->userPermissions, 'update tour') === false) ||
			($uIdentity->id == $tour['poster_id'] && strpos ($sess->userPermissions, 'update own tour') === false))
		{
		 	$this->view->errorMessage = __('Not allowed to edit this tour. Check if your session expired');
            $this->renderToHolder('common/error.phtml');
            return;
		}        
        
        //everything's fine. Continue editing
        $form = new Form_Tour();
        $form->cluBuild(array ('action' => 'edit', 'view' => $this->view, 'userPermissions' => $sess->userPermissions,'id' => $id));
                
        //populate the data  
		if($this->_request->isGet())
            $form->populate($this->m->transformToFormArray($tour));
			
        else if ($form->isValid($_POST))
        {	
			$data = $this->_request->getParams();
        	$articleData = array();
            $articleData['article_title'] = $data['name'];
            $articleData['article_body'] = $data['description'];
            $article_id = $tour['article']['article_id'];
            
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id,false))) //no validation
            	$this->view->errorMessage .= __("Could not update article");
            if ($this->m->saveRaw(null, $data, $id, false)) //don't pass tour obj because $tour is getTourData, not findByPrimary
            {
                $this->view->successMessage = __("Tour updated successfully");
            }
            else 
                $this->view->errorMessage = __("Could not update tour to DB");
        }
        else 
        	$this->view->errorMessage = __("Input is not valid");
        	
        $this->view->form = $form;
//        die_a($e);
		//$this->view->article_id = $e['article_id']; //for form submission
        $this->view->id = $id;
        
        $this->renderToHolder('index/new_tour.phtml');    
	}

	

	public function editTlegAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if(!$leg = $this->tl->getLegData($id, true)) //get leg article
        {              
            $this->view->errorMessage = __('Cannot find the requested event');
            $this->renderToHolder('common/error.phtml');
            return;
        }
        //tour authentication
        if(!$tour = $this->m->findByPrimary($leg['tid'])) //get tour article & tour leg article
        {              
            $this->view->errorMessage = __('Cannot find the requested tour');
            $this->renderToHolder('common/error.phtml');
            return;
        }
        
		//check for permission here
		//check rights
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = __('Not allowed to edit this tour. Check if your logged in session expired');
            $this->renderToHolder('common/error.phtml');
            return;
		}

		
		$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		//if not admin
		// or not owner
		if (($uIdentity->id != $tour['poster_id'] && strpos ($sess->userPermissions, 'update tour') === false) ||
			($uIdentity->id == $tour['poster_id'] && strpos ($sess->userPermissions, 'update own tour') === false))
		{
		 	$this->view->errorMessage = __('Not allowed to edit this user information. Check if your session expired');
            $this->renderToHolder('common/error.phtml');
            return;
		}        
        
        //everything's fine. Continue editing
        $form = new Form_TLeg();
        $form->cluBuild(array ('action' => 'edit', 'view' => $this->view, 'userPermissions' => $sess->userPermissions,'id' => $id));
                
        //populate the data
		if($this->_request->isGet())
            $form->populate($this->tl->transformToFormArray($leg));
			
        else if ($form->isValid($_POST))
        {	
			$data = $this->_request->getParams();
        	$articleData = array();
            //$articleData['article_title'] = $data['name'];
            $articleData['article_body'] = $data['description'];
            $article_id = $leg['article']['article_id'];
            
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id,false))) //no validation
            	$this->view->errorMessage .= __("Could not update article");
            if ($this->m->saveRaw(null, $data, $id, false)) //don't pass tour obj because $tour is getTourData, not findByPrimary
            {
                $this->view->successMessage = __("Tour updated successfully");
            }
            else 
                $this->view->errorMessage .= __("Could not update tour to DB");
        }
        else 
        	$this->view->errorMessage = __("Input is not valid");
        	
        $this->view->form = $form;
        $this->view->id = $id;
        
        $this->renderToHolder('index/new_tleg.phtml');    
	}
	
	public function searchAction()
    {
    	$data = $this->_request->getParams();
      	$form = new Form_TourSearch();
      	$form->cluBuild();
        $this->view->form = $form; 
		if($this->_request->isPost() && $form->isValid($_POST))
		{
	    	if($paginator = $this->m->search($data))
    		{
    			$paginator = $this->generatePaginator($paginator, 1, $data['tours_per_page'], 3, 'Jumping');
                $form->populate($data);  
    			
    			//cache in $_SESSION
               	$sess = new Zend_Session_Namespace("tour_paginator");
                $sess->tour_admin = array("search_params" => $data); 
        	}
		}
        else if(!empty($data['page']) && $data['page'] != null){
			$sess = new Zend_Session_Namespace("tour_paginator");
        	$data = $sess->tour_admin;
           	if(isset($data))
           	{
               $select = $this->m->search($data['search_params']);
               $paginator = $this->generatePaginator($select, $this->_getParam('page'), $data['search_params']['tours_per_page'], 3, 'Jumping');
               $form->populate($data['search_params']);//populate form
           	}
        }

        if(isset($paginator))
       	{                
            $this->view->paginator = $paginator;
            $tourList = $this->m->transformToViewData($paginator->getCurrentItems());
    		$this->view->tourList = $tourList;//list of found events
            $this->renderToHolder('index/list.phtml', false, null, 4,2); 
       	}
        $this->renderToHolder('index/search.phtml',false, null, 4,1); //search box 
    }
    
	public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setCurrentPageNumber($pageNumber);
        $paginator->setPageRange($pageRange);
        Zend_Paginator::setDefaultScrollingStyle($style);
        return $paginator;
    }

	public function successAction()
    {
         $this->view->tid =  $this->_request->getParam("tid");
         $this->renderToHolder( 'common/success.phtml');  
    }
}
?>
